/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.chaptersviewer;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.openbookformat.project.BookProp;
import org.openbookformat.project.Chapter;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;

/**
 *
 * @author MUFEED
 */
public class BookChildren extends Children.Keys implements Observer {
    BookProp bookProp;

    public BookChildren(BookProp bookProp) {
        this.bookProp = bookProp;
        //System.out.println("Setting the keys");
        setKeys(bookProp.getChapters());
    }

    @Override
    protected void addNotify() {
        setKeys(bookProp.getChapters());
    }


    @Override
    protected Node[] createNodes(Object key) {
        //System.out.println("Create Nodes:" + ((Chapter) key).getTitle());
        ChapterNode node = null;
        try {
            node = new ChapterNode((Chapter) key,
                    DataObject.find(bookProp.getProject().getProjectDirectory().
                    getFileObject("src/" + ((Chapter) key).getTitle()
                    + ".obf")));
        } catch (DataObjectNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
        node.setDisplayName(((Chapter) key).getTitle());
        return new Node[]{ node };
    }

    @Override
    public void update(Observable o, Object obj) {
        List array = (List) obj;
        if(!array.isEmpty() && array.get(0) instanceof Chapter)
            setKeys(array); 
    }
}
